const { uploadDir, createContext, readData, pushLog } = require('../common/operate');
var { APIOK, APIError } = require('../common/status');
var fs = require('fs');
var path = require('path');

var fn_upload = async (ctx, next) => {
    let id = ctx.request.body.id || false
    let name = ctx.request.body.name || false
    let token = ctx.headers.mytoken || false
    if (id && name) {
        if (readData(id) == token) {
            const file = ctx.request.files.file;
            try {
                createContext(id, name);
                const reader = fs.createReadStream(file.path);
                let filePath = path.join(uploadDir, `/${id}/${name}`) + `/${file.name}`;
                try {
                    fs.accessSync(filePath)
                    APIError(ctx, 406, '文件已存在')
                }
                catch (e) {
                    const upStream = fs.createWriteStream(filePath);
                    reader.pipe(upStream);
                    pushLog(id, name, file.name, '上传文件', '成功')
                    APIOK(ctx, {
                        path: file.name,
                    })
                }
            }
            catch (e) {
                console.log('捕捉', err)
            }
        } else {
            pushLog(id, name, 0, '上传文件', '权限不通过')
            APIError(ctx, 403, '权限不通过')
        }
    } else {
        APIError(ctx, 400, '参数错误')
    }
}

module.exports = fn_upload